from PySide6.QtWidgets import (QWidget, QVBoxLayout, QPushButton, QLabel, 
                             QLineEdit, QDialog, QMessageBox, QComboBox, QHBoxLayout, QCheckBox, QApplication, QTableWidget, QTableWidgetItem, QHeaderView)
from PySide6.QtCore import Qt
import sqlite3
import hashlib
import jwt
import datetime
from PySide6.QtCore import QSettings
from PySide6.QtCore import Signal

class UserCenter(QDialog):
    # 添加用户状态改变信号
    user_status_changed = Signal()
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowFlags(Qt.Popup | Qt.FramelessWindowHint)
        self.setup_ui()
        self.init_db()
        self.current_user = None
        self.load_current_user()
        
    def setup_ui(self):
        self.setFixedWidth(200)
        layout = QVBoxLayout(self)
        layout.setSpacing(8)  # 减小按钮之间的间距
        layout.setContentsMargins(10, 10, 10, 10)
        
        # 用户信息显示
        self.user_info = QLabel()
        self.user_info.setAlignment(Qt.AlignLeft)
        self.user_info.setStyleSheet("""
            QLabel {
                padding: 5px;
                color: #333333;
                font-size: 13px;
            }
        """)
        layout.addWidget(self.user_info)
        
        # 统一的按钮样式 - 减小按钮尺寸
        button_style = """
            QPushButton {
                background-color: #0066FF;
                color: white;
                border: none;
                border-radius: 3px;
                padding: 5px;
                font-size: 12px;
                min-height: 25px;
                max-height: 25px;
            }
            QPushButton:hover {
                background-color: #0052CC;
            }
            QPushButton:pressed {
                background-color: #004499;
            }
        """
        
        # 创建所有按钮并应用样式
        self.login_btn = QPushButton("登录")
        self.register_btn = QPushButton("注册")
        self.change_password_btn = QPushButton("修改密码")
        self.edit_info_btn = QPushButton("编辑信息")
        self.manage_users_btn = QPushButton("管理用户")
        self.logout_btn = QPushButton("切换账号")
        
        # 设置按钮点击事件
        self.login_btn.clicked.connect(self.show_login_dialog)
        self.register_btn.clicked.connect(self.show_register_dialog)
        self.change_password_btn.clicked.connect(self.show_change_password_dialog)
        self.edit_info_btn.clicked.connect(self.show_edit_info_dialog)
        self.manage_users_btn.clicked.connect(self.show_manage_users_dialog)
        self.logout_btn.clicked.connect(self.logout)
        
        # 应用样式并添加到布局
        buttons = [self.login_btn, self.register_btn, self.change_password_btn,
                  self.edit_info_btn, self.manage_users_btn, self.logout_btn]
        
        for btn in buttons:
            btn.setStyleSheet(button_style)
            layout.addWidget(btn)
            btn.hide()  # 初始隐藏所有按钮
        
        self.login_btn.show()  # 默认只显示登录按钮
        
        # 添加底部空白
        layout.addStretch()
        
    def init_db(self):
        conn = sqlite3.connect('device_config/config_file/users.db')
        cursor = conn.cursor()
        
        try:
            # 检查是否需要更新表结构
            cursor.execute("PRAGMA table_info(users)")
            columns = [column[1] for column in cursor.fetchall()]
            
            # 如果需要更新表结构
            if 'name' not in columns or 'occupation' not in columns:
                # 创建临时表
                cursor.execute('''
                    CREATE TABLE users_new (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        username TEXT UNIQUE NOT NULL,
                        password TEXT NOT NULL,
                        name TEXT,
                        occupation TEXT,
                        role TEXT NOT NULL,
                        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                    )
                ''')
                
                # 迁移现有数据
                cursor.execute('''
                    INSERT INTO users_new (username, password, role, created_at)
                    SELECT username, password, role, created_at FROM users
                ''')
                
                # 删除旧表
                cursor.execute('DROP TABLE users')
                
                # 重命名新表
                cursor.execute('ALTER TABLE users_new RENAME TO users')
                
            else:
                # 如果表不存在，创建新表
                cursor.execute('''
                    CREATE TABLE IF NOT EXISTS users (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        username TEXT UNIQUE NOT NULL,
                        password TEXT NOT NULL,
                        name TEXT,
                        occupation TEXT,
                        role TEXT NOT NULL,
                        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                    )
                ''')
            
            # 检查是否存在默认管理员账号
            cursor.execute('SELECT 1 FROM users WHERE username = ?', ('admin',))
            if not cursor.fetchone():
                # 创建默认管理员账号，密码为 admin123
                default_password = hashlib.sha256('admin123'.encode()).hexdigest()
                cursor.execute('''
                    INSERT INTO users (username, password, name, role)
                    VALUES (?, ?, ?, ?)
                ''', ('admin', default_password, '管理员', '管理员'))
                
                # 在数据库创建成功后，显示默认账号信息
                QMessageBox.information(None, "提示", 
                    "已创建默认管理员账号：\n"
                    "用户名:admin\n"
                    "密码:123456\n"
                    "请及时修改密码！")
            
            conn.commit()
            
        except sqlite3.Error as e:
            print(f"数据库错误: {str(e)}")
            conn.rollback()
            
        finally:
            conn.close()
        
    def load_current_user(self):
        """从 JWT token 加载当前用户"""
        token = self.parent().settings.value('user_token')
        if token:
            try:
                payload = jwt.decode(token, 'your-secret-key', algorithms=['HS256'])
                # 从数据库获取用户的完整信息
                conn = sqlite3.connect('device_config/config_file/users.db')
                cursor = conn.cursor()
                cursor.execute('SELECT name, occupation FROM users WHERE username = ?', (payload['username'],))
                result = cursor.fetchone()
                if result:
                    payload['name'] = result[0] or ''  # 如果为None则设为空字符串
                    payload['occupation'] = result[1] or ''
                conn.close()
                
                self.current_user = payload
                self.update_ui_for_logged_in_user()
            except jwt.ExpiredSignatureError:
                self.current_user = None
                self.parent().settings.remove('user_token')
                
    def update_ui_for_logged_in_user(self):
        """更新UI显示已登录用户信息"""
        if self.current_user:
            # 构建显示文本，每项单独一行并左对齐
            user_info_text = [
                f"当前用户: {self.current_user['username']}"
            ]
            
            # 如果有姓名，添加姓名显示
            if self.current_user.get('name'):
                user_info_text.append(f"姓名: {self.current_user['name']}")
                
            # 如果有职位，添加职位显示
            if self.current_user.get('occupation'):
                user_info_text.append(f"职位: {self.current_user['occupation']}")
                
            # 添加角色显示
            user_info_text.append(f"角色: {self.current_user['role']}")
            
            # 使用换行符连接所有信息
            self.user_info.setText('\n'.join(user_info_text))
            
            # 更新按钮显示状态
            self.login_btn.hide()
            self.change_password_btn.show()
            self.edit_info_btn.show()
            self.logout_btn.show()
            
            # 只有管理员才显示相关按钮
            if self.current_user['role'] == '管理员':
                self.register_btn.show()
                self.manage_users_btn.show()
            else:
                self.register_btn.hide()
                self.manage_users_btn.hide()
            
            # 发送用户状态改变信号
            self.user_status_changed.emit()
        else:
            self.user_info.setText("未登录")
            self.login_btn.show()
            self.register_btn.hide()
            self.change_password_btn.hide()
            self.edit_info_btn.hide()
            self.manage_users_btn.hide()
            self.logout_btn.hide()
            
            # 发送用户状态改变信号
            self.user_status_changed.emit()
            
    def show_login_dialog(self):
        dialog = LoginDialog(self)
        if dialog.exec_() == QDialog.Accepted:
            self.load_current_user()
            
    def show_register_dialog(self):
        """显示注册对话框 - 仅管理员可用"""
        if not self.current_user or self.current_user['role'] != '管理员':
            QMessageBox.warning(self, "权限不足", "只有管理员可以注册新用户")
            return
            
        dialog = RegisterDialog(self)
        dialog.exec_()  # 移除成功提示，只在 RegisterDialog 中显示
        
    def logout(self):
        """切换账号"""
        # 先退出当前账号
        self.current_user = None
        self.parent().settings.remove('user_token')
        self.update_ui_for_logged_in_user()
        
        # 关闭用户中心面板
        self.close()
        
        # 显示登录对话框
        dialog = LoginDialog(self)
        if dialog.exec_() == QDialog.Accepted:
            self.load_current_user()  # 重新加载用户信息
            QMessageBox.information(self, "成功", "切换账号成功")
        else:
            QMessageBox.information(self, "提示", "取消切换账号")
    
    def show_change_password_dialog(self):
        """显示修改密码对话框"""
        dialog = ChangePasswordDialog(self)
        dialog.exec_()
    
    def show_edit_info_dialog(self):
        dialog = EditUserInfoDialog(self)
        if dialog.exec_() == QDialog.Accepted:
            self.load_current_user()  # 刷新显示
            
    def show_manage_users_dialog(self):
        dialog = ManageUsersDialog(self)
        dialog.exec_()

class LoginDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("登录")
        self.settings = QSettings('Netconf', 'Netconf.cloud')  # 添加设置对象
        self.setup_ui()
        self.center_on_screen()
        self.load_saved_credentials()  # 加载保存的凭据
        
    def setup_ui(self):
        self.setFixedSize(400, 250)  # 设置固定大小
        layout = QVBoxLayout(self)
        layout.setSpacing(15)  # 设置控件间距
        layout.setContentsMargins(40, 20, 40, 20)  # 设置边距
        
        # 添加输入框
        self.username = QLineEdit()
        self.username.setPlaceholderText("请输入用户名")
        self.username.setMinimumHeight(40)
        self.username.setStyleSheet("""
            QLineEdit {
                border: 1px solid #DCDFE6;
                border-radius: 4px;
                padding: 0 10px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border-color: #0066FF;
            }
        """)
        layout.addWidget(self.username)
        
        self.password = QLineEdit()
        self.password.setPlaceholderText("请输入密码")
        self.password.setEchoMode(QLineEdit.Password)
        self.password.setMinimumHeight(40)
        self.password.setStyleSheet(self.username.styleSheet())
        layout.addWidget(self.password)
        # # 添加密码显示按钮
        # show_password_btn = QPushButton("显示密码")
        # show_password_btn.setMinimumHeight(40)
        # show_password_btn.setStyleSheet(self.username.styleSheet())
        # layout.addWidget(show_password_btn)
        # show_password_btn.clicked.connect(self.show_password)

        # # 添加密码隐藏按钮
        # hide_password_btn = QPushButton("隐藏密码")
        # hide_password_btn.setMinimumHeight(40)
        # hide_password_btn.setStyleSheet(self.username.styleSheet())
        # layout.addWidget(hide_password_btn)
        # hide_password_btn.clicked.connect(self.hide_password)

        default_layout = QHBoxLayout()
        default_username = QLabel("默认用户名:admin")
        default_password = QLabel("默认密码:123456  请及时修改密码!")
        default_layout.addWidget(default_username)
        default_layout.addWidget(default_password)
        layout.addLayout(default_layout)
        

        # 记住账号密码复选框
        remember_layout = QHBoxLayout()
        self.remember = QCheckBox("记住账号密码")

        self.remember.setStyleSheet("""
            QCheckBox {
                color: #666666;
                font-size: 12px;
            }
        """)
        # 设置记住密码的初始状态
        remembered = self.settings.value('remember_credentials', False, type=bool)
        self.remember.setChecked(remembered)
        
        remember_layout.addWidget(self.remember)
        remember_layout.addStretch()
        layout.addLayout(remember_layout)
        
        # 登录按钮
        login_btn = QPushButton("登录")
        login_btn.setMinimumHeight(40)
        login_btn.setStyleSheet("""
            QPushButton {
                background-color: #0066FF;
                color: white;
                border: none;
                border-radius: 4px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #0052CC;
            }
            QPushButton:pressed {
                background-color: #004499;
            }
        """)
        login_btn.clicked.connect(self.login)
        layout.addWidget(login_btn)
        
        # 添加一些空白空间
        layout.addStretch()
        
    def center_on_screen(self):
        """将窗口居中显示在屏幕上"""
        screen_geometry = QApplication.primaryScreen().availableGeometry()
        x = (screen_geometry.width() - self.width()) // 2
        y = (screen_geometry.height() - self.height()) // 2
        self.move(x, y)
        
    def load_saved_credentials(self):
        """加载保存的账号密码"""
        if self.settings.value('remember_credentials', False, type=bool):
            saved_username = self.settings.value('saved_username', '')
            saved_password = self.settings.value('saved_password', '')
            self.username.setText(saved_username)
            self.password.setText(saved_password)
    
    def save_credentials(self, username, password):
        """保存账号密码"""
        if self.remember.isChecked():
            self.settings.setValue('remember_credentials', True)
            self.settings.setValue('saved_username', username)
            self.settings.setValue('saved_password', password)
        else:
            self.settings.setValue('remember_credentials', False)
            self.settings.remove('saved_username')
            self.settings.remove('saved_password')
    
    def login(self):
        username = self.username.text()
        password = self.password.text()
        
        if not username or not password:
            QMessageBox.warning(self, "错误", "请填写完整信息")
            return
            
        conn = sqlite3.connect('device_config/config_file/users.db')
        cursor = conn.cursor()
        
        try:
            cursor.execute('SELECT password, role FROM users WHERE username = ?', (username,))
            result = cursor.fetchone()
            
            if result and result[0] == hashlib.sha256(password.encode()).hexdigest():
                # 生成 JWT token
                token = jwt.encode({
                    'username': username,
                    'role': result[1],
                    'exp': datetime.datetime.utcnow() + datetime.timedelta(days=7)
                }, 'your-secret-key', algorithm='HS256')
                
                # 保存 token
                self.parent().parent().settings.setValue('user_token', token)
                
                # 保存或清除凭据
                self.save_credentials(username, password)
                
                QMessageBox.information(self, "成功", "登录成功,请重启软件!")
                self.accept()
            else:
                QMessageBox.warning(self, "错误", "用户名或密码错误")

                
        finally:
            conn.close()

class RegisterDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("注册")
        self.setup_ui()
        self.center_on_screen()
        
    def setup_ui(self):
        self.setFixedSize(400, 400)  # 增加高度以容纳更多字段
        layout = QVBoxLayout(self)
        layout.setSpacing(15)
        layout.setContentsMargins(40, 20, 40, 20)
        
        # 用户名输入框
        self.username = QLineEdit()
        self.username.setPlaceholderText("请输入用户名")
        self.username.setMinimumHeight(40)
        self.username.setStyleSheet("""
            QLineEdit {
                border: 1px solid #DCDFE6;
                border-radius: 4px;
                padding: 0 10px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border-color: #0066FF;
            }
        """)
        layout.addWidget(self.username)
        
        # 姓名输入框（可选）
        self.name = QLineEdit()
        self.name.setPlaceholderText("请输入姓名（可选）")
        self.name.setMinimumHeight(40)
        self.name.setStyleSheet(self.username.styleSheet())
        layout.addWidget(self.name)
        
        # 密码输入框
        self.password = QLineEdit()
        self.password.setPlaceholderText("请输入密码")
        self.password.setEchoMode(QLineEdit.Password)
        self.password.setMinimumHeight(40)
        self.password.setStyleSheet(self.username.styleSheet())
        layout.addWidget(self.password)
        
        # 确认密码输入框
        self.confirm_password = QLineEdit()
        self.confirm_password.setPlaceholderText("请确认密码")
        self.confirm_password.setEchoMode(QLineEdit.Password)
        self.confirm_password.setMinimumHeight(40)
        self.confirm_password.setStyleSheet(self.username.styleSheet())
        layout.addWidget(self.confirm_password)
        
        # 职业选择（可选）
        self.occupation = QComboBox()
        self.occupation.addItems(["请选择职业（可选）", "网络工程师", "系统工程师", "运维工程师", "其他"])
        self.occupation.setMinimumHeight(40)
        self.occupation.setStyleSheet("""
            QComboBox {
                border: 1px solid #DCDFE6;
                border-radius: 4px;
                padding: 0 10px;
                font-size: 14px;
                background-color: white;
            }
            QComboBox:focus {
                border-color: #0066FF;
            }
            QComboBox::drop-down {
                border: none;
                width: 30px;
            }
            QComboBox::down-arrow {
                image: url(Icon/down_arrow.png);
                width: 12px;
                height: 12px;
            }
        """)
        layout.addWidget(self.occupation)
        
        # 用户角色选择
        self.role = QComboBox()
        self.role.addItems(["普通用户", "管理员"])
        self.role.setMinimumHeight(40)
        self.role.setStyleSheet(self.occupation.styleSheet())
        layout.addWidget(self.role)
        
        # 注册按钮
        register_btn = QPushButton("注册")
        register_btn.setMinimumHeight(40)
        register_btn.setStyleSheet("""
            QPushButton {
                background-color: #0066FF;
                color: white;
                border: none;
                border-radius: 4px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #0052CC;
            }
            QPushButton:pressed {
                background-color: #004499;
            }
        """)
        register_btn.clicked.connect(self.register)
        layout.addWidget(register_btn)
        
        # 添加一些空白空间
        layout.addStretch()
        
    def center_on_screen(self):
        """将窗口居中显示在屏幕上"""
        screen_geometry = QApplication.primaryScreen().availableGeometry()
        x = (screen_geometry.width() - self.width()) // 2
        y = (screen_geometry.height() - self.height()) // 2
        self.move(x, y)
        
    def register(self):
        username = self.username.text()
        name = self.name.text()
        password = self.password.text()
        confirm_password = self.confirm_password.text()
        occupation = self.occupation.currentText()
        role = self.role.currentText()
        
        # 如果职业是默认选项，则设为空
        if occupation == "请选择职业（可选）":
            occupation = ""
        
        if not username or not password or not confirm_password:
            QMessageBox.warning(self, "错误", "请填写必填信息")
            return
            
        if password != confirm_password:
            QMessageBox.warning(self, "错误", "两次输入的密码不一致")
            return
            
        conn = sqlite3.connect('device_config/config_file/users.db')
        cursor = conn.cursor()
        
        try:
            # 检查用户名是否已存在
            cursor.execute('SELECT 1 FROM users WHERE username = ?', (username,))
            if cursor.fetchone():
                QMessageBox.warning(self, "错误", "用户名已存在")
                return
                
            # 修改表结构（如果需要）
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS users (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    username TEXT UNIQUE NOT NULL,
                    password TEXT NOT NULL,
                    name TEXT,
                    occupation TEXT,
                    role TEXT NOT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
            ''')
            
            # 密码加密存储
            hashed_password = hashlib.sha256(password.encode()).hexdigest()
            
            # 插入新用户
            cursor.execute(
                'INSERT INTO users (username, password, name, occupation, role) VALUES (?, ?, ?, ?, ?)',
                (username, hashed_password, name, occupation, role)
            )
            conn.commit()
            
            QMessageBox.information(self, "成功", "注册成功")
            self.accept()
            
        except sqlite3.Error as e:
            QMessageBox.warning(self, "错误", f"注册失败: {str(e)}")
            
        finally:
            conn.close()

# 添加修改密码对话框类
class ChangePasswordDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("修改密码")
        self.setup_ui()
        self.center_on_screen()
        
    def setup_ui(self):
        self.setFixedSize(400, 250)
        layout = QVBoxLayout(self)
        layout.setSpacing(15)
        layout.setContentsMargins(40, 20, 40, 20)
        
        # 原密码输入框
        self.old_password = QLineEdit()
        self.old_password.setPlaceholderText("请输入原密码")
        self.old_password.setEchoMode(QLineEdit.Password)
        self.old_password.setMinimumHeight(40)
        self.old_password.setStyleSheet("""
            QLineEdit {
                border: 1px solid #DCDFE6;
                border-radius: 4px;
                padding: 0 10px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border-color: #0066FF;
            }
        """)
        layout.addWidget(self.old_password)
        
        # 新密码输入框
        self.new_password = QLineEdit()
        self.new_password.setPlaceholderText("请输入新密码")
        self.new_password.setEchoMode(QLineEdit.Password)
        self.new_password.setMinimumHeight(40)
        self.new_password.setStyleSheet(self.old_password.styleSheet())
        layout.addWidget(self.new_password)
        
        # 确认新密码输入框
        self.confirm_password = QLineEdit()
        self.confirm_password.setPlaceholderText("请确认新密码")
        self.confirm_password.setEchoMode(QLineEdit.Password)
        self.confirm_password.setMinimumHeight(40)
        self.confirm_password.setStyleSheet(self.old_password.styleSheet())
        layout.addWidget(self.confirm_password)
        
        # 确认按钮
        confirm_btn = QPushButton("确认修改")
        confirm_btn.setMinimumHeight(40)
        confirm_btn.setStyleSheet("""
            QPushButton {
                background-color: #0066FF;
                color: white;
                border: none;
                border-radius: 4px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #0052CC;
            }
            QPushButton:pressed {
                background-color: #004499;
            }
        """)
        confirm_btn.clicked.connect(self.change_password)
        layout.addWidget(confirm_btn)
        
    def center_on_screen(self):
        """将窗口居中显示在屏幕上"""
        screen_geometry = QApplication.primaryScreen().availableGeometry()
        x = (screen_geometry.width() - self.width()) // 2
        y = (screen_geometry.height() - self.height()) // 2
        self.move(x, y)
        
    def change_password(self):
        old_password = self.old_password.text()
        new_password = self.new_password.text()
        confirm_password = self.confirm_password.text()
        
        if not all([old_password, new_password, confirm_password]):
            QMessageBox.warning(self, "错误", "请填写完整信息")
            return
            
        if new_password != confirm_password:
            QMessageBox.warning(self, "错误", "两次输入的新密码不一致")
            return
            
        # 获取当前用户信息
        token = self.parent().parent().settings.value('user_token')
        if not token:
            QMessageBox.warning(self, "错误", "未登录状态")
            return
            
        try:
            user_info = jwt.decode(token, 'your-secret-key', algorithms=['HS256'])
            username = user_info['username']
            
            conn = sqlite3.connect('device_config/config_file/users.db')
            cursor = conn.cursor()
            
            # 验证原密码
            cursor.execute('SELECT password FROM users WHERE username = ?', (username,))
            result = cursor.fetchone()
            
            if not result or result[0] != hashlib.sha256(old_password.encode()).hexdigest():
                QMessageBox.warning(self, "错误", "原密码错误")
                return
                
            # 更新密码
            new_password_hash = hashlib.sha256(new_password.encode()).hexdigest()
            cursor.execute('UPDATE users SET password = ? WHERE username = ?', 
                         (new_password_hash, username))
            conn.commit()
            
            QMessageBox.information(self, "成功", "密码修改成功")
            self.accept()
            
        except jwt.ExpiredSignatureError:
            QMessageBox.warning(self, "错误", "登录已过期，请重新登录")
        except jwt.InvalidTokenError:
            QMessageBox.warning(self, "错误", "无效的登录状态")
        finally:
            if 'conn' in locals():
                conn.close() 

# 添加用户信息修改对话框类
class EditUserInfoDialog(QDialog):
    def __init__(self, parent=None, target_username=None):
        super().__init__(parent)
        self.target_username = target_username  # 要修改的目标用户名
        self.is_admin = False
        self.setup_ui()
        self.center_on_screen()
        self.load_user_info()
        
    def setup_ui(self):
        self.setWindowTitle("修改用户信息")
        self.setFixedSize(400, 450)  # 增加高度以容纳密码字段
        layout = QVBoxLayout(self)
        layout.setSpacing(15)
        layout.setContentsMargins(40, 20, 40, 20)
        
        # 用户名输入框（仅管理员可见）
        self.username_input = QLineEdit()
        self.username_input.setPlaceholderText("请输入用户名")
        self.username_input.setMinimumHeight(40)
        self.username_input.setStyleSheet("""
            QLineEdit {
                border: 1px solid #DCDFE6;
                border-radius: 4px;
                padding: 0 10px;
                font-size: 14px;
            }
            QLineEdit:focus {
                border-color: #0066FF;
            }
        """)
        self.username_input.hide()  # 默认隐藏
        layout.addWidget(self.username_input)
        
        # 密码输入框（仅管理员可见）
        self.password_input = QLineEdit()
        self.password_input.setPlaceholderText("请输入新密码（可选）")
        self.password_input.setEchoMode(QLineEdit.Password)
        self.password_input.setMinimumHeight(40)
        self.password_input.setStyleSheet(self.username_input.styleSheet())
        self.password_input.hide()  # 默认隐藏
        layout.addWidget(self.password_input)
        
        # 确认密码输入框（仅管理员可见）
        self.confirm_password = QLineEdit()
        self.confirm_password.setPlaceholderText("请确认新密码")
        self.confirm_password.setEchoMode(QLineEdit.Password)
        self.confirm_password.setMinimumHeight(40)
        self.confirm_password.setStyleSheet(self.username_input.styleSheet())
        self.confirm_password.hide()  # 默认隐藏
        layout.addWidget(self.confirm_password)
        
        # 姓名输入框
        self.name_input = QLineEdit()
        self.name_input.setPlaceholderText("请输入姓名")
        self.name_input.setMinimumHeight(40)
        self.name_input.setStyleSheet(self.username_input.styleSheet())
        layout.addWidget(self.name_input)
        
        # 职业选择
        self.occupation = QComboBox()
        self.occupation.addItems(["请选择职业", "网络工程师", "系统工程师", "运维工程师", "其他"])
        self.occupation.setMinimumHeight(40)
        self.occupation.setStyleSheet("""
            QComboBox {
                border: 1px solid #DCDFE6;
                border-radius: 4px;
                padding: 0 10px;
                font-size: 14px;
                background-color: white;
            }
            QComboBox:focus {
                border-color: #0066FF;
            }
            QComboBox::drop-down {
                border: none;
                width: 30px;
            }
        """)
        layout.addWidget(self.occupation)
        
        # 在职业选择后添加角色选择（仅管理员可见）
        self.role_select = QComboBox()
        self.role_select.addItems(["普通用户", "管理员"])
        self.role_select.setMinimumHeight(40)
        self.role_select.setStyleSheet(self.occupation.styleSheet())
        self.role_select.hide()  # 默认隐藏
        layout.addWidget(self.role_select)
        
        # 确认按钮
        confirm_btn = QPushButton("确认修改")
        confirm_btn.setMinimumHeight(40)
        confirm_btn.setStyleSheet("""
            QPushButton {
                background-color: #0066FF;
                color: white;
                border: none;
                border-radius: 4px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #0052CC;
            }
            QPushButton:pressed {
                background-color: #004499;
            }
        """)
        confirm_btn.clicked.connect(self.save_changes)
        layout.addWidget(confirm_btn)
        
        layout.addStretch()
        
    def center_on_screen(self):
        screen_geometry = QApplication.primaryScreen().availableGeometry()
        x = (screen_geometry.width() - self.width()) // 2
        y = (screen_geometry.height() - self.height()) // 2
        self.move(x, y)
        
    def load_user_info(self):
        # 获取 token 的路径修改
        token = None
        parent = self.parent()
        while parent:
            if hasattr(parent, 'settings'):
                token = parent.settings.value('user_token')
                break
            if hasattr(parent, 'parent') and callable(parent.parent):
                parent = parent.parent()
            else:
                break
            
        if not token:
            return
            
        try:
            user_info = jwt.decode(token, 'your-secret-key', algorithms=['HS256'])
            self.is_admin = user_info['role'] == '管理员'
            
            # 确定要加载的用户名
            username_to_load = self.target_username if self.target_username else user_info['username']
            
            conn = sqlite3.connect('device_config/config_file/users.db')
            cursor = conn.cursor()
            
            cursor.execute('SELECT username, name, occupation, role FROM users WHERE username = ?', 
                         (username_to_load,))
            result = cursor.fetchone()
            
            if result:
                if self.is_admin and self.target_username:  # 只有管理员编辑其他用户时显示
                    self.username_input.show()
                    self.password_input.show()
                    self.confirm_password.show()
                    self.role_select.show()
                    self.username_input.setText(result[0])
                    # 设置当前角色
                    role_index = self.role_select.findText(result[3])
                    if role_index >= 0:
                        self.role_select.setCurrentIndex(role_index)
                self.name_input.setText(result[1] or '')
                if result[2]:
                    index = self.occupation.findText(result[2])
                    if index >= 0:
                        self.occupation.setCurrentIndex(index)
                        
        except (jwt.ExpiredSignatureError, jwt.InvalidTokenError):
            QMessageBox.warning(self, "错误", "登录已过期，请重新登录")
        finally:
            if 'conn' in locals():
                conn.close()
                
    def save_changes(self):
        new_name = self.name_input.text()
        new_occupation = self.occupation.currentText()
        if new_occupation == "请选择职业":
            new_occupation = ""
            
        # 获取要修改的用户名
        username_to_update = self.target_username if self.target_username else self.parent().current_user['username']
        new_username = None
        new_password = None
        new_role = None
        
        # 如果是管理员，处理用户名、密码和角色的修改
        if self.is_admin and self.username_input.isVisible():
            new_username = self.username_input.text()
            if not new_username:
                QMessageBox.warning(self, "错误", "用户名不能为空")
                return
                
            # 检查密码修改
            if self.password_input.text():
                if self.password_input.text() != self.confirm_password.text():
                    QMessageBox.warning(self, "错误", "两次输入的密码不一致")
                    return
                new_password = hashlib.sha256(self.password_input.text().encode()).hexdigest()
                
            # 获取新角色
            if self.role_select.isVisible():
                new_role = self.role_select.currentText()
            
        conn = sqlite3.connect('device_config/config_file/users.db')
        cursor = conn.cursor()
        
        try:
            if new_username and new_username != username_to_update:
                # 检查新用户名是否已存在
                cursor.execute('SELECT 1 FROM users WHERE username = ? AND username != ?', 
                             (new_username, username_to_update))
                if cursor.fetchone():
                    QMessageBox.warning(self, "错误", "用户名已存在")
                    return
            
            # 构建更新语句
            update_fields = ['name = ?', 'occupation = ?']
            params = [new_name, new_occupation]
            
            if new_username:
                update_fields.append('username = ?')
                params.append(new_username)
                
            if new_password:
                update_fields.append('password = ?')
                params.append(new_password)
                
            if new_role:
                update_fields.append('role = ?')
                params.append(new_role)
                
            params.append(username_to_update)  # WHERE 子句的参数
            
            # 执行更新
            cursor.execute(f'''
                UPDATE users 
                SET {', '.join(update_fields)}
                WHERE username = ?
            ''', params)
            
            conn.commit()
            QMessageBox.information(self, "成功", "信息修改成功")
            self.accept()
            
        except sqlite3.Error as e:
            QMessageBox.warning(self, "错误", f"修改失败: {str(e)}")
        finally:
            conn.close() 

# 添加用户管理对话框类
class ManageUsersDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("用户管理")
        self.setup_ui()
        self.center_on_screen()
        self.load_users()
        
    def setup_ui(self):
        self.setFixedSize(600, 400)
        layout = QVBoxLayout(self)
        layout.setSpacing(15)
        layout.setContentsMargins(20, 20, 20, 20)
        
        # 用户列表
        self.user_list = QTableWidget()
        self.user_list.setColumnCount(6)
        self.user_list.setHorizontalHeaderLabels(["用户名", "姓名", "职位", "角色", "创建时间", "操作"])
        self.user_list.horizontalHeader().setStretchLastSection(True)
        self.user_list.setSelectionBehavior(QTableWidget.SelectRows)
        self.user_list.setEditTriggers(QTableWidget.NoEditTriggers)
        self.user_list.setStyleSheet("""
            QTableWidget {
                border: 1px solid #DCDFE6;
                border-radius: 4px;
                background-color: white;
            }
            QTableWidget::item {
                padding: 5px;
            }
            QHeaderView::section {
                background-color: #F5F7FA;
                padding: 5px;
                border: none;
                border-bottom: 1px solid #DCDFE6;
            }
        """)
        layout.addWidget(self.user_list)
        
        # 底部按钮
        button_layout = QHBoxLayout()
        close_btn = QPushButton("关闭")
        close_btn.setStyleSheet("""
            QPushButton {
                background-color: #FFFFFF;
                color: #606266;
                border: 1px solid #DCDFE6;
                border-radius: 4px;
                padding: 8px 16px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #F5F7FA;
                border-color: #C0C4CC;
            }
        """)
        close_btn.clicked.connect(self.close)
        button_layout.addStretch()
        button_layout.addWidget(close_btn)
        layout.addLayout(button_layout)
        
    def center_on_screen(self):
        screen_geometry = QApplication.primaryScreen().availableGeometry()
        x = (screen_geometry.width() - self.width()) // 2
        y = (screen_geometry.height() - self.height()) // 2
        self.move(x, y)
        
    def load_users(self):
        conn = sqlite3.connect('device_config/config_file/users.db')
        cursor = conn.cursor()
        
        try:
            cursor.execute('''
                SELECT username, name, occupation, role, created_at 
                FROM users 
                ORDER BY created_at DESC
            ''')
            users = cursor.fetchall()
            
            self.user_list.setRowCount(len(users))
            for row, user in enumerate(users):
                # 添加用户信息
                for col, value in enumerate(user):
                    item = QTableWidgetItem(str(value or ''))
                    self.user_list.setItem(row, col, item)
                
                # 添加操作按钮
                button_widget = QWidget()
                button_layout = QHBoxLayout(button_widget)
                button_layout.setContentsMargins(5, 0, 5, 0)
                button_layout.setSpacing(5)
                
                # 编辑按钮
                edit_btn = QPushButton("编辑")
                edit_btn.setStyleSheet("""
                    QPushButton {
                        background-color: #409EFF;
                        color: white;
                        border: none;
                        border-radius: 4px;
                        padding: 5px 10px;
                    }
                    QPushButton:hover {
                        background-color: #66B1FF;
                    }
                """)
                edit_btn.clicked.connect(lambda checked, u=user[0]: self.edit_user(u))
                
                # 删除按钮
                delete_btn = QPushButton("删除")
                delete_btn.setStyleSheet("""
                    QPushButton {
                        background-color: #F56C6C;
                        color: white;
                        border: none;
                        border-radius: 4px;
                        padding: 5px 10px;
                    }
                    QPushButton:hover {
                        background-color: #F78989;
                    }
                """)
                delete_btn.clicked.connect(lambda checked, u=user[0]: self.delete_user(u))
                
                button_layout.addWidget(edit_btn)
                button_layout.addWidget(delete_btn)
                button_layout.addStretch()
                
                self.user_list.setCellWidget(row, 5, button_widget)
            
            # 调整列宽
            self.user_list.resizeColumnsToContents()
            
        except sqlite3.Error as e:
            QMessageBox.warning(self, "错误", f"加载用户列表失败: {str(e)}")
        finally:
            conn.close()
            
    def edit_user(self, username):
        dialog = EditUserInfoDialog(self, username)
        if dialog.exec_() == QDialog.Accepted:
            self.load_users()  # 刷新用户列表
            
    def delete_user(self, username):
        # 防止删除自己
        current_user = self.parent().current_user['username']
        if username == current_user:
            QMessageBox.warning(self, "错误", "不能删除当前登录用户")
            return
            
        reply = QMessageBox.question(self, "确认删除", 
                                   f"确定要删除用户 {username} 吗？",
                                   QMessageBox.Yes | QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            conn = sqlite3.connect('device_config/config_file/users.db')
            cursor = conn.cursor()
            
            try:
                cursor.execute('DELETE FROM users WHERE username = ?', (username,))
                conn.commit()
                QMessageBox.information(self, "成功", "用户删除成功")
                self.load_users()  # 刷新用户列表
            except sqlite3.Error as e:
                QMessageBox.warning(self, "错误", f"删除失败: {str(e)}")
            finally:
                conn.close() 